package org.jeecgframework.web.system.controller.core;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.extend.datasource.DataSourceContextHolder;
import org.jeecgframework.core.extend.datasource.DataSourceType;
import org.jeecgframework.core.util.ContextHolderUtils;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.IpUtil;
import org.jeecgframework.core.util.PasswordUtil;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.web.service.CbsInspectionEvaluateServiceI;
import org.jeecgframework.web.service.CbsVerificationCodeServiceI;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.system.manager.ClientManager;
import org.jeecgframework.web.system.pojo.base.CbsVerificationCodeEntity;
import org.jeecgframework.web.system.pojo.base.Client;
import org.jeecgframework.web.system.pojo.base.TSBaseUser;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSRoleUser;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.pojo.base.ZyEngineerEntity;
import org.jeecgframework.web.system.service.MutiLangServiceI;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.system.service.UserService;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * APP 登陆初始化控制器
 */
@Scope("prototype")
@Controller
@RequestMapping("/loginAppController")
public class LoginAppController extends BaseController {

    @Autowired
    private ZyCommonService zyCommonService;

    private SystemService systemService;
    private UserService userService;
    private String message = null;


    @Autowired
    private CbsVerificationCodeServiceI cbsVerificationCodeServiceI;

    @Autowired
    private MutiLangServiceI mutiLangService;

    @Autowired
    private CbsInspectionEvaluateServiceI cbsInspectionEvaluateServiceI;

    @Autowired
    public void setSystemService(SystemService systemService) {
        this.systemService = systemService;
    }

    @Autowired
    public void setUserService(UserService userService) {

        this.userService = userService;
    }

    /**
     * 保存用户登录的信息，并将当前登录用户的组织机构赋值到用户实体中；
     *
     * @param req   request
     * @param user  当前登录用户
     * @param orgId 组织主键
     */
    private void saveLoginSuccessInfo(HttpServletRequest req, TSUser user, String orgId) {
        TSDepart currentDepart = systemService.get(TSDepart.class, orgId);
        user.setCurrentDepart(currentDepart);

        HttpSession session = ContextHolderUtils.getSession();
        message = mutiLangService.getLang("common.user") + ": " + user.getUserName() + "["
                + currentDepart.getDepartname() + "]" + mutiLangService.getLang("common.login.success");

        Client client = new Client();
        client.setIp(IpUtil.getIpAddr(req));
        client.setLogindatetime(new Date());
        client.setUser(user);

        session.setAttribute("c_user_id", user.getId());
        session.setAttribute("c_depart_id", orgId);

        ClientManager.getInstance().addClinet(session.getId(), client);
        // 添加登陆日志
        systemService.addLog(message, Globals.Log_Type_LOGIN, Globals.Log_Leavel_INFO);
    }


    /**
     * @author xiul
     * 2016-10-28 下午2:36:48
     * Description 给APPsession续命
     */
    @ResponseBody
    @RequestMapping(params = "countinueSessionLife")
    public void countinueSessionLife(HttpServletRequest request) {
        System.err.println("成功续命一次" + DateUtils.date2Str(new Date(), DateUtils.datetimeFormat));
    }

    /**
     * @author xiul
     * 2016-8-3 下午7:05:14
     * Description App 跳转 登录验证
     */
    @ResponseBody
    @RequestMapping(params = "goAppLoginCheck")
    public AjaxJson goAppLoginCheck(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        Map<String, Object> rsMap = new HashMap<String, Object>();
        TSUser user = ResourceUtil.getSessionUserName();
        String phone = user.getMobilePhone();//133*****888

        rsMap.put("uid", user.getId());
        if (StringUtil.isNotEmpty(phone) && phone.length() >= 11) {
            rsMap.put("relPhone", phone);
            rsMap.put("mobilePhone", phone.substring(0, 3) + "*****" + phone.substring(8));
        }
        j.setAttributes(rsMap);
        return j;
    }

    /**
     * @author xiul
     * 2016-8-1 下午5:57:21
     * Description 用户登录 验证码
     */
    @ResponseBody
    @RequestMapping(params = "sendRandomCode")
    public AjaxJson sendRandomCode(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        try {
            String uid = oConvertUtils.getString(req.getParameter("uid"));
            TSUser user = systemService.get(TSUser.class, uid);
            String mobilePhone = user.getMobilePhone();
            j = cbsVerificationCodeServiceI.userLoginCheck(mobilePhone);
        } catch (Exception e) {
            j.setMsg(e.getMessage());
            j.setSuccess(false);
        }
        return j;
    }

    /**
     * 检查用户名称
     *
     * @param user
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "checkuser")
    public AjaxJson checkuser(TSUser user, HttpServletRequest req) {
        System.out.println("APP登录检查登录信息。。。。");
        DataSourceContextHolder.setDataSourceType(DataSourceType.dataSource_jeecg);
        req.getSession().setAttribute("lang", "zh-cn");
        AjaxJson j = new AjaxJson();
        int users = userService.getList(TSUser.class).size();
        if (users == 0) {
            j.setMsg("系统用户为空");
            j.setSuccess(false);
        } else {
            TSUser u = userService.checkAppUserExits(user);
            if (null == u) {
                j.setMsg("用户名或密码错误");
                j.setSuccess(false);
                return j;
            }
            TSUser u2 = userService.getEntity(TSUser.class, u.getId());

            if (u != null && u2.getStatus() != 0) {
                Map<String, Object> attrMap = new HashMap<String, Object>();
                j.setAttributes(attrMap);

                String orgId = req.getParameter("orgId");
                if (oConvertUtils.isEmpty(orgId)) { // 没有传组织机构参数，则获取当前用户的组织机构
                    Long orgNum = systemService.getCountForJdbc("select count(1) from t_s_user_org where user_id = '" + u.getId() + "'");
                    if (orgNum > 1) {
                        attrMap.put("orgNum", orgNum);
                        attrMap.put("user", u2);
                    } else {
                        Map<String, Object> userOrgMap = systemService.findOneForJdbc("select org_id as orgId from t_s_user_org where user_id=?", u2.getId());
                        saveLoginSuccessInfo(req, u2, (String) userOrgMap.get("orgId"));
                    }
                } else {
                    attrMap.put("orgNum", 1);
                    saveLoginSuccessInfo(req, u2, orgId);
                }
            } else {
                j.setMsg("用户已经禁用");
                j.setSuccess(false);
            }
        }
        return j;
    }

    /**
     * @author xiul
     * 2016-7-29 上午10:50:47
     * Description 找回APP密码 - 第一步 检查信息
     */
    @ResponseBody
    @RequestMapping(params = "retrievePwdCheckInfo")
    public AjaxJson retrievePwdCheckInfo(
            @RequestParam(value = "mobilePhone") String mobilePhone,
            @RequestParam(value = "verificationCode") String verificationCode) {
        AjaxJson j = new AjaxJson();
        HttpSession session = ContextHolderUtils.getSession();
        try {
            if (!verificationCode.equalsIgnoreCase(oConvertUtils.getString(session.getAttribute("randCode")))) {
                j.setSuccess(false);
                message = "验证码输入错误";
            } else {
                List<TSUser> tsusers = systemService.findHql("from TSUser where mobilePhone=?", mobilePhone);
                if (tsusers.size() > 0) {
                    TSUser user = tsusers.get(0);
                    j.setObj(user.getId());
                } else {
                    j.setSuccess(false);
                    message = "没有查找到该用户";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            j.setSuccess(false);
        }
        j.setMsg(message);
        return j;
    }


    /**
     * @param request
     * @author xiul
     * 2016年7月29日 下午5:21:57
     * Description 找回APP密码 - 根据手机号发送验证码
     */
    @ResponseBody
    @RequestMapping(params = "sendRetrievePwdRandomCode")
    public AjaxJson sendRetrievePwdRandomCode(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            String mobilePhone = oConvertUtils.getString(request.getParameter("mobilePhone"));
            j = cbsVerificationCodeServiceI.userRetrievePassword(mobilePhone);
        } catch (Exception e) {
            e.printStackTrace();
            j.setSuccess(false);
        }
        return j;
    }

    /**
     * @author xiul
     * 2016-8-2 下午3:18:43
     * Description 验证短信验证码是否正确 以及是否超时
     */
    @ResponseBody
    @RequestMapping(params = "checkVerificationCode")
    public AjaxJson checkVerificationCode(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        try {
            String verficationCode = oConvertUtils.getString(req.getParameter("verficationCode"));
            String busType = oConvertUtils.getString(req.getParameter("busType"));
            if (StringUtil.isEmpty(verficationCode)) {
                j.setSuccess(false);
                message = "验证码为空";
            } else {
                AjaxJson rs = zyCommonService.checkUserRandomCodeTimeout(ContextHolderUtils.getSession().getId(), busType, verficationCode);
                if (!rs.isSuccess()) {//验证不通过
                    message = rs.getMsg();
                    j.setSuccess(rs.isSuccess());
                } else {
                    if (!busType.equals(StaticValue.RANDOMCODE_RETRIEVE_PWD)) {//找回密码这里 当前seesion里没有登录用户
                        TSUser user = ResourceUtil.getSessionUserName();
                        j.setObj(user.getId());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            j.setSuccess(false);
        }
        j.setMsg(message);
        return j;
    }


    /**
     * @author xiul
     * 2016年7月29日 下午4:44:05
     * Description 找回APP密码 - 验证两次输入的密码是否一致 并修改密码
     */
    @ResponseBody
    @RequestMapping(params = "checkPasswordWhenRetrievePwd")
    public AjaxJson checkPasswordWhenRetrievePwd(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            String uid = oConvertUtils.getString(request.getParameter("uid"));
            String pwd = oConvertUtils.getString(request.getParameter("password"));
            String rpwd = oConvertUtils.getString(request.getParameter("rePassword"));
            if (!pwd.equals(rpwd)) {
                j.setSuccess(false);
                message = "您两次输入的密码不一致";
            } else {
                TSBaseUser bUser = systemService.getEntity(TSBaseUser.class, uid);
                if (null == bUser) {
                    message = "用户不存在";
                    j.setSuccess(false);
                } else {
                    pwd = PasswordUtil.encrypt(bUser.getUserName(), pwd, PasswordUtil.getStaticSalt());
                    bUser.setAppPassword(pwd);
                    systemService.saveOrUpdate(bUser);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            j.setSuccess(false);
            message = "系统异常";
        }
        j.setMsg(message);
        return j;

    }

    /**
     * 退出系统
     */
    @ResponseBody
    @RequestMapping(params = "logout")
    public void logout(HttpServletRequest request) {
        HttpSession session = ContextHolderUtils.getSession();
        ClientManager.getInstance().removeClinet(session.getId());
    }

    /**
     * 首页跳转
     */
    @ResponseBody
    @RequestMapping(params = "goAppHomePage")
    public AjaxJson goAppHomePage(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            TSUser user = ResourceUtil.getSessionUserName();
            user = systemService.getEntity(TSUser.class, user.getId());
            if (null == user) {
                request.getSession().setAttribute("lang", "zh-cn");
                String _webkit_uid = oConvertUtils.getString(request.getParameter("_webkit_uid"));
                user = systemService.getEntity(TSUser.class, _webkit_uid);
                Map<String, Object> userOrgMap = systemService.findOneForJdbc("select org_id as orgId from t_s_user_org where user_id=?", user.getId());
                saveLoginSuccessInfo(request, user, (String) userOrgMap.get("orgId"));
            }
            returnMap.put("headFileLogId", null == user.getHeadFileLogId() ? "" : user.getHeadFileLogId());
            returnMap.put("userName", user.getRealName());

            String ipListView = "";
            String serviceListView = "";
            List<TSRoleUser> tsRoleUser = systemService.findHql("from TSRoleUser where TSUser.id = ?", user.getId());
            String userType = "";
            if (null != tsRoleUser && tsRoleUser.size() > 0) {
                for (TSRoleUser rsRU : tsRoleUser) {
                    cbsInspectionEvaluateServiceI.getUserInspectionEvaluates(rsRU.getTSRole().getRoleCode(), returnMap);
                    //优先级 第三方负责人 > 区域工程师 > 工程师 > 物流 > CSA
                    if (rsRU.getTSRole().getRoleCode().equals(StaticValue.RULE_CODE_THIRDPARTY_HEADER)) {
                        ipListView = "../app_inspection_plan/appIpListOfTp.html";//app端页面结构
                        serviceListView = "../app_servicing/appServiceListOfTp.html";//app端页面结构
                        userType = "1";
                        break;
                    }
                    if (rsRU.getTSRole().getRoleCode().equals(StaticValue.RULE_CODE_AREA_ENGINEER)) {
                        ipListView = "../app_inspection_plan/appIpListOfAeg.html";
                        serviceListView = "../app_servicing/appServiceListOfAeg.html";//app端页面结构

                        userType = "2";
                        break;
                    }
                    if (rsRU.getTSRole().getRoleCode().equals(StaticValue.RULE_CODE_THIRDPARTY_ENGINEER)) {
                        ipListView = "../app_inspection_plan/appIpListOfEg.html";
                        serviceListView = "../app_servicing/appServiceListOfEg.html";//app端页面结构

                        userType = "2";
                        break;
                    }
                    if (rsRU.getTSRole().getRoleCode().equals(StaticValue.CBS_WL_ROLE_CODE)) {  //物流
//                        ipListView = "../app_inspection_plan/appIpListOfEg.html";
                        serviceListView = "../app_servicing/appServiceShipListLogistics.html";//app端页面结构

                        userType = "3";
                        break;
                    }
                    if (rsRU.getTSRole().getRoleCode().equals(StaticValue.RULE_CODE_BARCO_CSA)) {  //CSA
//                        ipListView = "../app_inspection_plan/appIpListOfEg.html";
                        serviceListView = "../app_servicing/appServiceShipList.html";//app端页面结构

                        userType = "4";
                        break;
                    }
                }
            }
            if (userType.equals("2")) {//如果是工程师，查询对应的信息
                List<ZyEngineerEntity> egs = systemService.findByProperty(ZyEngineerEntity.class, "tsBaseUser.id", user.getId());
                if (null != egs && egs.size() > 0) {//工程师认证证书
                    returnMap.put("authentication", egs.get(0).getAuthentication());
                    returnMap.put("egNo", egs.get(0).getEngineerNo());
                }
            }
            returnMap.put("userType", userType);
            returnMap.put("ipListView", ipListView);//巡检计划列表页跳转页面
            returnMap.put("serviceListView", serviceListView);//维修列表页跳转页面
        } catch (Exception e) {
            j.setMsg("请求数据异常");
            j.setSuccess(false);
            e.printStackTrace();
        }

        j.setAttributes(returnMap);
        return j;
    }

    /**
     * @author xiul
     * 2016-9-28 上午11:26:53
     * Description APP - 评分详细页
     */
    @ResponseBody
    @RequestMapping(params = "queryUserIes")
    public AjaxJson queryUserIes(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        boolean flag = true;
        try {
            List<Map<String, Object>> rsMapList = cbsInspectionEvaluateServiceI.queryUserIes(req);
            j.setObj(rsMapList);
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
            message = "评分数据查询失败";
        }
        j.setSuccess(flag);
        j.setMsg(message);
        return j;
    }

    /**
     * 无权限页面提示跳转
     *
     * @return
     */
    @RequestMapping(params = "noAuth")
    public ModelAndView noAuth(HttpServletRequest request) {
        return new ModelAndView("common/noAuth");
    }

    /**
     * @author xiul
     * 2016-8-3 下午12:51:00
     * Description 跳转到 设置中心
     */
    @RequestMapping(params = "goSetting")
    public ModelAndView goSetting() {
        return new ModelAndView("com/app/app_login/setting");
    }

    /**
     * @author xiul
     * 2016-8-3 下午12:59:33
     * Description 跳转 反馈页面
     */
    @RequestMapping(params = "goFeedback")
    public ModelAndView goFeedback() {
        return new ModelAndView("com/app/app_login/feedback");
    }

    /**
     * @author xiul
     * 2016-8-3 下午12:53:31
     * Description 关于 barco
     */
    @RequestMapping(params = "aboutBarco")
    public ModelAndView aboutBarco() {
        return new ModelAndView("com/app/app_login/aboutBarco");
    }

}